/**
 * Created by Administrator on 2017/2/8.
 */
var goods_id = getQueryString('goods_id');
var my_store_id = getQueryString('mystore_id');

    $(function () {

    var key = getCookie('key');

    function initPage() {
        $.ajax({
            type: 'get',
            url: ApiUrl + "/index.php?act=goods&op=goods_detail",
            data: {goods_id:goods_id,key: key},
            dataType: 'json',
            success: function (result) {
                  console.log(result);
                  if(result['code']==200){
                      data = result.datas;
                      //商品图片格式化数据
                      if(data.goods_image){
                          var goods_image = data.goods_image.split(",");
                          data.goods_image = goods_image;
                      }else{
                          data.goods_image = [];
                      }
                      //商品规格格式化数据
                      if(data.goods_info.spec_name){
                          var goods_map_spec = $.map(data.goods_info.spec_name,function (v,i){
                              var goods_specs = {};
                              goods_specs["goods_spec_id"] = i;
                              goods_specs['goods_spec_name']=v;
                              if(data.goods_info.spec_value){
                                  $.map(data.goods_info.spec_value,function(vv,vi){
                                      if(i == vi){
                                          goods_specs['goods_spec_value'] = $.map(vv,function (vvv,vvi){
                                              var specs_value = {};
                                              specs_value["specs_value_id"] = vvi;
                                              specs_value["specs_value_name"] = vvv;
                                              return specs_value;
                                          });
                                      }
                                  });
                                  return goods_specs;
                              }else{
                                  data.goods_info.spec_value = [];
                              }
                          });
                          data.goods_map_spec = goods_map_spec;
                      }else {
                          data.goods_map_spec = [];
                      }

                      var html_image = template.render('image_tpl',data);
                      $("#imgsPaly").html(html_image);
                      var html_goods_info = template.render('goods_tmpl',data);
                      $("#g_name_header_tpl").html(html_goods_info);
                      var html_goods2 = template.render('goods2_tmpl',data);
                      $("#g_name_p_html").html(html_goods2);
                      var html_Buy = template.render('buy_tpl',data);
                      $(".buy1").html(html_Buy);
                      var goods_evel = template.render('goods_evel',data);
                      $("#goods_eva").html(goods_evel);
                      //// 渲染body;
                      $("#details-info").html("<h3>商品详情</h3>"+data.goods_info['mobile_body']);
                      var goods_by = template.render('buy_tpl',data);
                      $(".buy").html(goods_by);
                      var goods_list = template.render('goods_list',data);
                      $("#good_list").html(goods_list);
                      $('.car_count').html(getCookie('cart_count'));

                      var myData = {};
                      myData["spec_list"] = data.spec_list;

                      $('.ultwo li').on('touchstart',function(){
                          $(this).addClass('active').siblings().removeClass('active')
                          var self = this;
                          arrowClick(self,myData);
                      })
                      $('.buy1').on('touchstart',function(ev){
                          var ev=ev||event;
                          ev.stopPropagation();
                      })
                      //图片轮播
                      picSwipe();
                      // var swiper = new Swiper('.swiper-container', {
                      //     pagination: '.swiper-pagination',
                      //     paginationClickable: true
                      // });
                      // var swiper = new Swiper('.swiper-container');
                  }
            }
        });
    }
    // 图片轮播
    function picSwipe(){
        var elem = $(".swiper-container")[0];
        window.mySwipe = Swipe(elem, {
            continuous: false,
            // disableScroll: true,
            stopPropagation: true,
            callback: function(index, element) {
                $('.goods-detail-turn').find('li').eq(index).addClass('cur').siblings().removeClass('cur');
            }
        });
    }
    //点击商品规格，获取新的商品
    function arrowClick(self,myData){
        //拼接属性
        var curEle = $(".ultwo").find("li.active");
        var curSpec = [];
        $.each(curEle,function (i,v){
            // convert to int type then sort
            curSpec.push(parseInt($(v).attr("specs_value_id")) || 0);
        });
        var spec_string = curSpec.sort(function(a, b) { return a - b; }).join("|");
        console.log(myData.spec_list);
        //获取商品ID
        goods_id = myData.spec_list[spec_string];
        initPage();
    }

//初始化页面
    initPage();
});
//加入购物车
function addCar(){
    var key = getCookie('key');//登录标记
    var quantity = parseInt($('.shuliang').html());
    if(!key){
        creatLayout('请登录后进行操作');
        var goods_info = decodeURIComponent(getCookie('goods_cart'));
        if (goods_info == null) {
            goods_info = '';
        }
        if(goods_id<1){
            return false;
        }
        var cart_count = 0;
        if(!goods_info){
            goods_info = goods_id+','+quantity;
            cart_count = 1;
        }else{
            var goodsarr = goods_info.split('|');
            for (var i=0; i<goodsarr.length; i++) {
                var arr = goodsarr[i].split(',');
                if(contains(arr,goods_id)){
   9            }
            }
            goods_info+='|'+goods_id+','+quantity;
            cart_count = goodsarr.length;
        }
        // 加入cookie
        addCookie('goods_cart',goods_info);
        // 更新cookie中商品数量
        addCookie('cart_count',cart_count);
        getCartCount();
        return false;
    }else{
        $.ajax({
            url:ApiUrl+"/index.php?act=member_cart&op=cart_add",
            data:{key:key,goods_id:goods_id,quantity:quantity},
            type:"post",
            success:function (result){
                var rData = $.parseJSON(result);
                if(checkLogin(rData.login)){
                    if(!rData.datas.error){
                        // 更新购物车中商品数量
                        delCookie('cart_count');
                        getCartCount();
                        $('.car_count').html(getCookie('cart_count'));
                        creatLayout("添加购物车成功")
                    }else{
                        creatLayout(rData.datas.error);
                    }
                }
            }
        })
    }
}
function buyNow(){
      var num = $('.shuliang').html();
      param = '';
      if (goods_id){
          param += "goods_id="+goods_id;
      }
      if (num){
          param += "&buynum="+num;
      }
      if(my_store_id){
           param += '&my_store_id='+my_store_id;
      }
      var url = WapSiteUrl+"/tmpl/order/buy_step1.html?"+param;
      window.location.href = url;
}